package com.test12;

class Phone {
    private String brand;   // 品牌
    private double price;   // 价格

    public Phone(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    @Override
    public String toString() {
        return "【手机】品牌：" + this.brand + "、价格：" + this.price;
    }
}

class Resource {
    private Phone phone;
    private int number = 0;

    public synchronized void create(String brand, double price) {
        try {
            while (this.phone != null) {
                super.wait();
            }
            this.phone = new Phone(brand, price);
            System.out.println(Thread.currentThread().getName() + "：生产第" + (++this.number) + "台" + this.phone);
            super.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void sale() {
        try {
            while (this.phone == null) {
                super.wait();
            }
            System.out.println(Thread.currentThread().getName() + "：销售第" + (this.number) + "台" + this.phone);
            this.phone = null;
            super.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class MyTest_02 {

    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                if (i % 2 == 0) {
                    resource.create("华为P30", 4800.0);
                } else {
                    resource.create("IPhone13", 5900.0);
                }
            }
        }, "手机厂家").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                resource.sale();
            }
        }, "黑心商家").start();
    }
}
